import { useRef } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, DatePicker, Select, Table, Tag } from 'antd';
import { DataNode } from 'antd/es/tree';
import { Dayjs } from 'dayjs';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { StatusObj } from '@/enum/product';
import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import { proMeetingTaskPage } from '@/services/bizApi/shengchanhuiyirenwujiekou';
import { findIdByName } from '@/utils';

import Dispose, { DisposeRef } from './dispose';
import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProMeetingTaskEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const dispose = useRef<DisposeRef>(null);
  const [filter] = Filter.useForm();
  const treeDict = useRef<Record<number, DataNode>>({});
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const table = useAntdTable(
    async ({ current, pageSize }, { id, taskDispatchTime, ...formData }) => {
      const [taskDispatchTimeBegin, taskDispatchTimeEnd] = (
        (taskDispatchTime as [Dayjs?, Dayjs?]) || []
      ).map((v) => v?.format('YYYY-MM-DD HH:mm:ss'));
      const res = await proMeetingTaskPage({
        ...formData,
        ...id,
        taskDispatchTimeBegin,
        taskDispatchTimeEnd,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="taskDispatchTime">
          <DatePicker.RangePicker showTime placeholder={['任务下发开始时间', '任务下发结束时间']} />
        </Filter.Item>
        <Filter.Item name="dispatchUserId">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择安排人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Filter.Item>
        <Filter.Item name="dutyUserId">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择责任人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Filter.Item>

        <Filter.Item name="importance">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择重要性"
            options={[
              { value: '重要', label: '重要' },
              { value: '普通', label: '普通' },
              { value: '其他', label: '其他' }
            ]}
          />
        </Filter.Item>
        <Filter.Item name="taskType">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择工作类型"
            options={[
              { value: '生产早会', label: '生产早会' },
              { value: '其他', label: '其他' }
            ]}
          />
        </Filter.Item>
        <Filter.Item name="status">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择任务状态"
            options={[
              { value: 1, label: '待处理' },
              { value: 3, label: '已完成' }
            ]}
          />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '重要性',
            dataIndex: 'importance'
          },
          {
            title: '任务内容',
            dataIndex: 'taskContent'
          },
          {
            title: '工作类型',
            dataIndex: 'taskType'
          },
          {
            title: '任务下发时间',
            dataIndex: 'taskDispatchTime'
          },
          {
            title: '要求完成时间',
            dataIndex: 'requiredCompletionTime'
          },
          {
            title: '安排日期',
            dataIndex: 'dispatchDate'
          },
          {
            title: '安排人',
            dataIndex: 'dispatchUserId',
            render: (text) => userInfo?.data?.filter((item) => item.id === text)?.[0]?.fullName
          },
          {
            title: '部门',
            dataIndex: 'dutyDeptId',
            render: (text) => findIdByName(tree?.data || [], text as unknown as string)
          },
          {
            title: '责任人',
            dataIndex: 'dutyUserId',
            render: (text) => userInfo?.data?.filter((item) => item.id === text)?.[0]?.fullName
          },
          {
            title: '任务状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = StatusObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '执行情况说明',
            dataIndex: 'handleSituation'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() &&
                    row?.status === 1 &&
                    row?.dutyUserId === store?.user?.id && (
                      <Text
                        onClick={() => {
                          dispose.current?.open({
                            rowData: row,
                            onSuccess: () => {
                              table.refresh();
                            }
                          });
                        }}
                        type="primary"
                      >
                        处理
                      </Text>
                    )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <Dispose ref={dispose} />
    </>
  );
};

export default Page;
